﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using HJ212_Protocol;
using SailHero.Soft.ESB.Communication.ClientAndServer.Client;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.EndPoints.Tcp;
using SailHero.Soft.ESB.Communication.ClientAndServer.Communication.Messages;

namespace HJT212_Protocol_WebHostClient
{
    public partial class IndexStart : System.Web.UI.Page
    {
        #region PageLoad
        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                Response.Cache.SetNoStore();

                CheckIsConnected();

                if (IsPostBack)
                {
                    toMN = Request["selcedMN"];
                    var _msgToshow = Session["msgToshow"];
                    if (_msgToshow != null)
                    {
                        msgToshow = (string)_msgToshow;
                    }
                }
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        #endregion

        #region 属性字段
        private IClient client;
        private string toMN = "";
        private string msgToshow = "";
        #endregion

        #region 事件




        public void btnConn_Click(object sender, EventArgs e)
        {
            try
            {

                if (CheckIsConnected())
                {
                    return;
                }
                this.txtBoxContent.Text = "";
                string _port = ConfigurationManager.AppSettings["SrvPort"];
                string ProtocolSrv = ConfigurationManager.AppSettings["ProtocolSrv"];
                client = ClientFactory.CreateClient(new ESBTcpEndPoint(ProtocolSrv, Convert.ToInt32(_port)));
                client.MessageReceived += Client_MessageReceived;
                client.WireProtocol = new MyWireProtocol(); //Set custom wire protocol!
                client.MN = ConfigurationManager.AppSettings["MN"];
                client.PW = ConfigurationManager.AppSettings["PW"];
                client.Disconnected += client_Disconnected;
                client.Connect();
                btnSend.Enabled = true;
                string msg = "已经正确连接了服务端\r\n";
                this.txtBoxContent.Text += (msg);
                this.btnConn.Enabled = false;
                Session["client"] = client;

                var url = HttpContext.Current.Request.Url;
                Response.Redirect(url.AbsolutePath);
            }
            catch (Exception ex)
            {
                //throw;
            }
        }

        private void client_Disconnected(object sender, EventArgs e)
        {
            try
            {
                string msg = "服务器强制踢出！\r\n";
                this.btnConn.Enabled = true;
                this.txtBoxContent.Text += msg;
            }
            catch (Exception ex)
            {

                throw;
            }
        }

        public void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                string[] str1 = new string[60];
                for (int i = 0; i < 60; i++)
                {
                    str1[i] = "1";
                }
                string[] str2 = new string[60];
                for (int i = 0; i < 60; i++)
                {
                    str2[i] = "2";
                }
                string to = toMN;
                string str = this.txtMsgToSend.Text;
                TextMessage Tmsg = new TextMessage(str);
                Tmsg.FromMN = string.Format("{0}{1}", client.MN, "");
                Tmsg.To = string.Join("", str2);
                client.SendMessage(Tmsg);
            }
            catch (Exception ex)
            {
                throw;
            }
        }

        private void Client_MessageReceived(object sender, MessageEventArgs e)
        {
            //Client only accepts text messages            
            var message = e.Message as TextMessage;
            if (message == null)
            {
                return;
            }
            string msg = message.Text + "\r\n";
            msgToshow += msg;
            Session["msgToshow"] = msgToshow;
            //存入数据库的操作
        }


        #endregion

        #region 方法

        private bool CheckIsConnected()
        {
            try
            {
                labMsg.ForeColor = Color.Green;
                labMsg.Text = "未连接";
                var clt = Session["client"];
                if (clt != null)
                {
                    IClient clnt = (IClient)clt;
                    if (clnt.CommunicationState == CommunicationStates.Connected)
                    {
                        client = clnt;
                        this.btnConn.Enabled = false;
                        labMsg.ForeColor = Color.Red;
                        labMsg.Text = "已连接";
                        return true;
                    }

                }
            }
            catch (Exception ex)
            {
                //记录异常
            }
            return false;
        }

        #endregion
    }
}